<template>
  <div>
    <div id="tools">
    <!--停车场管理-->
      <div class="height8"></div>
      <!-- 查询条件 -->
      <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">

        <a-form-item label="选择日期" class="marginBtm">
          <a-config-provider :locale="localezh_CN">
            <a-range-picker @change="onChangePicker" :locale="localezh_CN" :default-value="[startDate, endDate]" format="YYYY-MM-DD HH:mm" :show-time="{ format: 'HH:mm' }"/>
          </a-config-provider>
        </a-form-item>

        <!--<a-form-item label="方向" class="marginBtm">-->
          <!--&lt;!&ndash;99全部1出2进&ndash;&gt;-->
          <!--<a-dropdown style="">-->
            <!--<a-menu slot="overlay" @click="handleMenuClick">-->
              <!--<a-menu-item :key="item.id" v-for="item in approvalStatus">{{item.name}}</a-menu-item>-->
            <!--</a-menu>-->
            <!--<a-button>{{ statusValue }}-->
              <!--<a-icon type="down"/>-->
            <!--</a-button>-->
          <!--</a-dropdown>-->
        <!--</a-form-item>-->

        <a-form-item label="名单类型" class="marginBtm">
          <!--99全部1出2进-->
          <a-dropdown style="">
            <a-menu slot="overlay" @click="isblackMenuClick">
              <a-menu-item :key="item.id" v-for="item in isblackStatus">{{item.name}}</a-menu-item>
            </a-menu>
            <a-button>{{ isblackValue }}
              <a-icon type="down"/>
            </a-button>
          </a-dropdown>
        </a-form-item>

        <a-form-item label="车辆类型" class="marginBtm">
          <!--99全部1出2进-->
          <a-dropdown style="">
            <a-menu slot="overlay" @click="carMenuClick">
              <a-menu-item :key="item.id" v-for="item in carstype">{{item.name}}</a-menu-item>
            </a-menu>
            <a-button>{{ carValue }}
              <a-icon type="down"/>
            </a-button>
          </a-dropdown>
        </a-form-item>

        <a-form-item label="关键字" class="marginBtm">
          <a-input v-model="queryValue" allowClear placeholder="请输入工号/姓名/车牌/电话" class="marginBtm"
                   @pressEnter="inquireStart"/>
        </a-form-item>

        <a-form-item class="marginBtm">
          <a-button type="primary" @click="inquireStart">
            查询
          </a-button>
        </a-form-item>

      </a-form>
      <a-divider style="margin: 5px 0"/>
      <div style="padding: 5px 10px 10px 10px;text-align: left;">
        <a-button type="primary" class="button-marin" @click="addDilog">
          新增
        </a-button>
        <a-button type="primary" class="button-marin" @click="modifyDilog">
          修改
        </a-button>
        <a-button type="primary" class="button-marin" @click="importList">
          导入
        </a-button>

        <a-button type="primary" class="button-marin" @click="exportList">
          导出
        </a-button>

      </div>
    </div>

    <a-table
      class="tabled"
      bordered
      :fixed="true"
      size="small"
      :columns="columns"
      :row-key="record => record.id"
      :rowSelection="{type:'radio',selectedRowKeys:selectedRowKeys,fixed:true,onChange:onChange}"
      :customRow="clickRow"
      :data-source="tableData"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ x:xWidth,y: yHeight }"
      :locale="localezh_CN"
      @change="handleTableChange"
    >
      <!--点击行选中行，点击单选按钮选中行；但是需要:row-key是唯一标示字段-->

      <!-- <template slot="name" slot-scope="name"> {{ name.first }} {{ name.last }} </template> -->
    </a-table>

  <!--导入--没有使用-->
    <a-modal
      title="导入"
      :visible="importVisible"
      :maskClosable="false"
      :keyboard="false"
      :footer="null"
      @cancel="importCancel"
    >
        <!--:before-upload="beforeUpload"-->
      <a-upload
      name="file"
      :action="uploadAction"
      @change="handleChange"
      :showUploadList="false"
      >
        <a-button type="primary" class="button-marin">
        选择文件
        </a-button>
      </a-upload>
      <p style="color: #ff4d4f;margin: 10px 0;">{{ errorMessage }}</p>
      <a-divider />
      <a-button type="primary" class="button-marin" @click="downTemplate">
        下载模板
      </a-button>
    </a-modal>


      <!--新增修改弹窗-->
      <collection-create-form
        ref="collectionForm"
        :visible="visible"
        :title="modalTitle"
        :confirmLoading="confirmLoading"
        @cancel="handleCancel"
        @create="handleCreate"
      />


  </div>
</template>

<script>
  import {tableBoxHeight} from "@/api/communal";
  import reservationApi from "@/api/reservation";
  import localezh_CN from 'antd/lib/locale-provider/zh_CN';
  import dateUtil from "@/utils/dateUtils";
  import moment from "moment";
  import {ConfigProvider} from 'ant-design-vue';//引用
  import 'moment/locale/zh-cn';
  import cfg from '@/config/config'
  import CollectionCreateForm from "@/components/createForm";


  export default {
    components: {
      ConfigProvider,
      CollectionCreateForm
    },
    name: '',
    data() {
      return {
        localezh_CN,
        spinning: false,
        importVisible: false,
        importLoading: false,
        fileList:[],
        errorMessage:"",
        uploadAction: cfg.apiUrl + 'api/parkingLot/importLeaves',
        carstype:[
          {name: "全部", id: 99},
        ],
        carValue: "全部",  //名单类型
        carId: "99",   //名单类型id，<!--99全部1出2进-->
        delayTime: 500,
        confirmLoading: false,
        modalData: null,
        xWidth: "",
        yHeight: "",
        tableData: [],
        modalTitle:"新增",
        pagination: {
          pageSize: 30,
          current: 1,
          total: 100,
          showSizeChanger: true,
          // showQuickJumper: true,
          pageSizeOptions: ['30', '50', '100'],
          showTotal: (total) => `共 ${total} 条`, // 显示总数
          onShowSizeChange: (current, pageSize) => {
            // console.log("1111");
            this.pagination.current = 1;
            this.pagination.pageSize = pageSize;
          },
        },
        selectedRowKeys: [],
        selectedRows: null,
        loading: false,
        dateFormat: 'YYYY/MM/DD HH:mm',
        startDate: "",
        endDate: "",
        startDated: "",
        endDated: "",
        modalStartDated: "",//弹窗开始日期
        modalEndDated: "",//弹窗结束日期
        queryValue: "",  //查询值,访客名称，访客手机号
        columns: [],   //表格表头
        statusValue: "",  //状态名称
        statusId: 99,   //状态id，<!--99全部1出2进-->
        approvalStatus: [
          {name: "全部", id: 99},
          {name: "出", id: 1},
          {name: "进", id: 2},
        ],

        isblackValue: "全部",  //名单类型
        isblackId: 99,   //名单类型id，<!--99全部1出2进-->
        isblackStatus: [
          {name: "全部", id: 99},
          {name: "白名单", id: 0},
          {name: "黑名单", id: 1},
          {name: "灰名单", id: 2},
        ],

        visible: false,
        isblack: 99,


      }
    },

    beforeMount() {

      this.columns = [
        {
          title: '序号',     //表头
          dataIndex: 'serialNumber',   //字段名称
          width: '50px',    //设列宽度
          align: 'center',  //居中显示
          className: 'changeBack',   //重置覆盖背景色为浅灰色，否则是白色的
          customRender: (value, row, index) => `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}`  //设置动态序号
        },
        {
          title: '车牌',
          dataIndex: 'chepai',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '车主',
          dataIndex: 'userName',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '工号',
          dataIndex: 'userNo',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '电话',
          dataIndex: 'userTelephone',
          width: 'auto',
          align: 'center',
          className: 'changeBack',
        },
        {
          title: '类型',
          dataIndex: 'lx',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '开始时间',
          dataIndex: 'startDate',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '结束时间',
          dataIndex: 'endDate',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        {
          title: '名单类型',
          dataIndex: 'isblackText',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
      ];
      // 名单类型
      // isblack 数字的名单类型 0 1 2
      // isblackText  字符串的名单类型  白名单  黑名单   灰名单
      this.startDate = moment().startOf('month');
      this.endDate = moment().endOf('month');
      this.startDated = moment(this.startDate).format('YYYY-MM-DD HH:mm');
      this.endDated = moment(this.endDate).format('YYYY-MM-DD HH:mm');
      this.getcarsTypeList();

    },
    mounted() {
      // console.log(tableBoxHeight());
      this.yHeight = tableBoxHeight() + 3  + "px";
      this.xWidth = this.getTableWidth();
      this.statusValue = this.approvalStatus[0].name;
      this.statusId = this.approvalStatus[0].id;
      let minHeight = document.getElementsByClassName("ant-table");
      minHeight[0].style.minHeight = tableBoxHeight() + 40 + "px";

      this.inquireStart();

    },
    methods: {

      // 计算表格宽度
      getTableWidth() {
        let totals = null;
        var el;
        for (el of this.columns) {
          totals += parseInt(el.width);
        }
        return totals + 100 + "px"
      },
      // 查询条件选择日期
      onChangePicker(date, dateString) {
        // console.log(date, dateString);
        this.startDated = dateString[0];
        this.endDated = dateString[1];
      },
      // 弹窗选择日期
      modalChangePicker(date, dateString) {
        // console.log(date, dateString);
        this.modalStartDated = dateString[0];
        this.modalEndDated = dateString[1];
      },

      // 导出列表
      exportList() {
        if (this.startDated == "") {
          this.$message.warning("开始日期不能为空");
          return
        }
        if (this.endDated == "") {
          this.$message.warning("结束日期不能为空");
          return
        }

        this.spinning = true;
        let param = {
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
          startDate: this.startDated,
          endDate: this.endDated,
          serchTxt: this.queryValue,
          isblack: this.isblackId,
        };
        let jsonIn = encodeURI(encodeURI(JSON.stringify(param)));
        window.open(cfg.apiUrl + 'api/parkingLot/exportDtAllcarsqList?jsonIn=' + jsonIn, "_self");
        this.spinning = false;

      },
      async downTemplate(){
        await window.open(cfg.apiUrl + "api/parkingLot/downLoad");
      },
      // 开始查询
      inquireStart() {
        this.pagination.current = 1;
        this.selectedRowKeys = [];
        this.selectedRows = null;
        // console.log(this.carId)
        // 如果增加查询条件，导出里面也要增加，条件一样
        let param = {
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
          startDate: this.startDated + ":00",  // 页面查询时精确到时分，但提交要精确到秒，否则现场环境后台报500
          endDate: this.endDated + ":59",
          serchTxt: this.queryValue,
          isblack: this.isblackId,
          vehicleTypeId: this.carId,
        };
        // console.log(param);
        this.fetch(param);
      },
      // 审批状态下拉菜单
      handleMenuClick(e) {
        // console.log(e);
        this.approvalStatus.filter(el => {
          if (el.id == e.key) {
            // console.log(el);
            this.statusValue = el.name;
            this.statusId = el.id
          }
        });
        // console.log(this.statusValue,this.statusId);
      },
      // 点击行
      clickRow(record) {
        return {
          on: {
            click: () => {
              console.log(record)
              let keys = [];
              keys.push(record.id);   //行数据一定要有唯一识别标志，否则无法选中，和表格的key一致
              this.selectedRowKeys = keys;
              this.selectedRows = record;
            }
          }
        }

      },
      // 表格切换分页
      handleTableChange(pagination, filters, sorter) {
        // console.log(pagination);
        const pager = {...this.pagination};
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetch({
          pageSize: pagination.pageSize,
          current: pagination.current,
          startDate: this.startDated,
          endDate: this.endDated,
          // approvalStatus: this.statusId,
          serchTxt: this.queryValue,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters,
        });
      },
      // 新增弹窗
      addDilog() {
        console.log(this.selectedRows);  // 行数据
        this.modalTitle = "新增";
        // 如果有行数据，就填充到弹窗中，没有则不处理
        if (this.selectedRows){
          this.visible = true;
          this.$nextTick(() => {
            this.$refs.collectionForm.stuffDilog(this.selectedRows,false);
          })
        } else {
          this.visible = true;
        }
      },
      // 修改弹窗
      modifyDilog() {
        // 如果有行数据，就填充到弹窗中，如果为null，则提示选一个人，修改时要考虑是否有些东西是不可修改的，
        console.log(this.selectedRows);  // 行数据如果没有，可以和新增共用一个方法
        this.modalTitle = "修改";
        if (this.selectedRows){
          this.visible = true;
          this.$nextTick(() => {
            this.$refs.collectionForm.stuffDilog(this.selectedRows,true);
          })
        } else {
          this.$message.warning("请选择要进行修改的数据");
        }
      },
      // 获取车辆类型
      async getcarsTypeList(){
        let resp = await reservationApi.getVehicleTypeList();
        if (resp.data.success){
          // console.log(resp.data.result)
          this.carstype = [...this.carstype,...resp.data.result];
        } else {
          this.$message.error(resp.data.message);
        }
      },
      async handleOk() {
        console.log(this.modalData);   //弹窗数据
        let startdated = moment(this.modalData.allDate[0]).format('YYYY-MM-DD HH:mm');
        let enddated = moment(this.modalData.allDate[1]).format('YYYY-MM-DD HH:mm');
        // console.log(startdated);   //开始日期
        // console.log(enddated);   //结束日期
        let lxname = this.carstype.filter(el=>{return el.id == this.modalData.statusId})[0].name;
        console.log(lxname);

        this.confirmLoading = true;  //提交按钮加载中
        // 处理提交事件
        let params = {
          chepai: this.modalData.licensePlate,
          endDate: enddated,
          id: this.modalTitle == "新增" ? 0:this.selectedRows.id,    //大于0修改，小于0添加
          lx: lxname,
          startDate: startdated,
          userName: this.modalData.userName,
          userNo: this.modalData.workNo,
          vehicleTypeId: this.modalData.statusId,
          isblack: this.modalData.isblack,
        };
        console.log(params);
        let resp = await reservationApi.savaDtAllcarsq(params);
        console.log(resp.data);
        if (resp.data.success) {
          this.confirmLoading = false;  //提交按钮加载中
          this.$refs.collectionForm.initFormValue();
          this.visible = false;   //关闭弹窗
          this.$message.success("保存成功");
          this.inquireStart();
        } else {
          this.confirmLoading = false;  //提交按钮加载中
          this.$message.error(resp.data.message);
        }

      },
      handleCancel() {
        this.$refs.collectionForm.initFormValue();
        this.confirmLoading = false;  //提交按钮加载中
        this.visible = false;
      },
  // 点击确认
      handleCreate() {
        let _this = this;
        const form = this.$refs.collectionForm.form;
        form.validateFields((err, values) => {
          if (err) {
            return;
          }
          console.log(values);
          this.modalData = values;
          _this.handleOk();
        });
      },

      onChange(selectedRowKeys, selectedRows) {
        console.log(selectedRowKeys, selectedRows);
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows[0];
      },
      // 名单类型下拉菜单
      isblackMenuClick(e) {
        // console.log(e);
        this.isblackStatus.filter(el => {
          if (el.id == e.key) {
            console.log(el);
            this.isblackValue = el.name;
            this.isblackId = el.id
          }
        });
        // console.log(this.statusValue,this.statusId);
      },
      // 车辆类型下拉菜单
      carMenuClick(e) {
        console.log(e);
        this.carstype.filter(el => {
          if (el.id == e.key) {
            console.log(el);
            this.carValue = el.name;
            this.carId = el.id
          }
        });
        // console.log(this.statusValue,this.statusId);
      },
      // 请求表格数据
      async fetch(params) {
        this.loading = true;
        let resp = await reservationApi.findDtAllcarsqList(params);
        // console.log(resp.data);
        if (resp.data.success) {
          this.loading = false;
          this.pagination.total = resp.data.result.total;
          this.tableData = resp.data.result.records;
          // 测试数据
//           this.tableData = [
//             {userNo: 12345,userName:"张三",chepai:"沪A185H7",
//               userTelephone:"13247586798",lx:"员工车辆",id: 0,startDate:"2020-12-12 8:13",endDate:"2021-12-12 17:00",orderId:12345},
//             {userNo: 12345,userName:"李四",chepai:"沪A18588",
//               userTelephone:"13247586799",lx:"VIP用户",id: 1,startDate:"2020-12-12 9:47",endDate:"2021-12-12 17:00",orderId:12346}
//           ]
        } else {
          this.loading = false;
          this.$message.error(resp.data.message);
        }

      },

      // 导入列表
      importList(){
        console.log("导入");
        this.errorMessage = '';
        this.importVisible = true;
      },
      beforeUpload(file) {
        // console.log(file);
      },
      handleChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success){
            // console.log(info.file.response.result);
            if (info.file.response.result.length > 0){
              this.errorMessage = info.file.response.result[0].errorMsg;
            } else {
              this.$message.success(`${info.file.name}`);  //导入成功
              this.importVisible = false;
              this.inquireStart();
            }

          } else {
            this.errorMessage = info.file.response.message;
            // this.$message.error(`${info.file.response.message}`);
          }

        } else if (info.file.status === 'error') {
          // this.$message.error(`${info.file.name}`);
          this.errorMessage = info.file.name
        }
      },
      importCancel(){
        this.importVisible = false
      }


    },
  }
</script>

<style scoped>
  .marginBtm {
    margin-bottom: 5px;
  }

</style>

